package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.INavService;
import com.cn.wanxi.util.EnumFileName;
import com.cn.wanxi.util.FileName;
import com.cn.wanxi.util.IO;
import com.cn.wanxi.util.Tool;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NavServiceImpl implements INavService {
    public static void main(String[] args) {
//        System.out.println(EnumFileName.FILE_NAV.getName());
        new NavServiceImpl().getNavModels();
    }

    @Override
    public NavModel[] getNavModels() {
//        1.创建文件
//        String fileName = "nav.txt";
        IO.createFile(EnumFileName.FILE_NAV.getName());
//        2.封装写入的数据
        List<String> data = getData();
//        3.写入记事本
        IO.writeData(data);
//        4.读取数据
        String result = IO.readData();
//        5.封装数据
        return setData(result);
    }

    /**
     * @param result
     * @return
     */
    private NavModel[] setData(String result) {
        System.out.println(result);
        result = Tool.replace(result);
        String[] results = result.split(FileName.FILE_SPLIT);
        String[] hrefs = results[0].split(", ");
        String[] titles = results[1].split(", ");
//        NavDao navDao = new NavDao();
        int length = hrefs.length;
        NavModel[] navModels = new NavModel[length];
        for (int i = 0; i < length; i++) {
            NavModel model = new NavModel();
            model.setHref(hrefs[i]);//取数组的值赋值给对象的属性
            model.setTitle(titles[i]);
            navModels[i] = model;//将对象赋值给数组
        }
        return navModels;
    }

    private List<String> getData() {
        List<String> list = new ArrayList<>();
        NavDao navDao = new NavDao();
        list.add(Arrays.toString(navDao.hrefs));
        list.add(Arrays.toString(NavDao.TITLES));
//        list.add(0);
//        list.add(true);
        return list;
    }

    /**
     * 只要出现两次及以上的代码 我们都要去提取公共部分
     *
     * @return
     */
//    private File createFile() {
//        String path = "";
//        File filePath = new File(path);
//        boolean exists = filePath.exists();
////        System.out.println(exists);
//        if (!exists) {
//            path = "E:\\wanxi\\step-3\\canyin03-0720\\web";
//            filePath = new File(path);
//        }
////        少些if else  可以if
////      创建包，文件夹
//        String directory = "note";
//        File fileDirectory = new File(filePath, directory);
//        if (!fileDirectory.exists()) {
//            boolean mkdir = fileDirectory.mkdirs();
//            System.out.println(mkdir);
//        }
//        String fileName = "nav.txt";
//        File file = new File(fileDirectory, fileName);
//        try {
//            file.createNewFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return file;
//    }
}
